import Mocha from '../../modules/mocha.js';
import RTLog from '../../modules/rt_log.js';
import { getMixedList } from './func.js';
const App = getApp();
let interstitialAd = null;

Page({
    data: {
        layout: '', // only-product-list
        groups: [],
        productAdvertiseList: [],
        products: [],
        productInfo: {},
        showList: [],
        adUnitId: null,
        count: 0,
        banner: '',
        currentDataList: [],
        product_layout: ''
    },
    onLoad() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        this.refresh().then(() => {
            wx.hideLoading();
        });

        this.xiguaAdMgrPool = getApp().$modules.advertise.getActivateVideoAdPool();
    },
    onPullDownRefresh() {
        wx.showNavigationBarLoading();
        this.refresh().then(() => {
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
        });
    },
    onShow() {
        this.refresh();
    },
    refresh() {
        return new Promise((resolve, reject) => {
            Mocha.getConfig()
                .then((cfg) => {
                    wx.hideLoading();
                    wx.setNavigationBarColor({
                        frontColor: cfg.theme.navibar_text_color || '#000000',
                        backgroundColor: cfg.theme.navibar_bkgnd_color || '#F5F5F5'
                    });
                    App.globalData.cfgData = cfg;
                    this.setData({
                        products: cfg.suggest,
                        productInfo: cfg,
                        isBgType: cfg.bg?.startsWith('#'),
                        banner: cfg.banner || ''
                    });
                    let { product_layout, suggest } = this.data.productInfo;
                    if (product_layout) {
                        if (product_layout == 'row') {
                            this.setData({
                                product_layout: 'row',
                                showList: suggest
                            }, () => {
                                resolve();
                            });
                        } else {
                            this.setData({
                                product_layout: 'line',
                                currentDataList: suggest
                            }, () => {
                                resolve();
                            });
                            this.changeProduct();
                        }
                    } else {
                        this.setData({
                            layout: 'only-product-list'
                        }, () => {
                            resolve();
                        });
                    }
                    getApp().mox.stat(`index page get_mocha_h5_config success`);
                })
                .catch((err) => {
                    // getApp().mox.stat(
                    //     `index page get_mocha_h5_config fail：${err.msg || err.errMsg || '未知错误'}`
                    // );
                    getApp().mox.stat(`index page get_mocha_h5_config fail`);
                    RTLog.error(
                        'index page get_mocha_h5_config fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    reject(err);
                });

            Mocha.getAdsConfig()
                .then((ads) => {
                    const ad = ads['pages/index/index'];
                    if (ad && ad.ad_id) {
                        if (ad.ad_type === 'interstitialad') {
                            this.toCreateInterstitialAd(ad.ad_id);
                        } else {
                            this.setData({ adUnitId: ad.ad_id });
                        }
                    }
                    if (ad && ad.random_ad_list) {
                        // 有设置广告列表
                        // 产品根据product_group_size分组，产品组和广告交替排布
                        let mixedList = getMixedList(
                            products,
                            ad.random_ad_list,
                            ad.product_group_size
                        );
                        this.setData({
                            layout: 'product-mixed-ads',
                            groups: mixedList
                        });
                    }
                    getApp().mox.stat(`index page get_ads_config success`);
                })
                .catch((err) => {
                    // getApp().mox.stat(
                    //     `index page get_ads_config fail：${err.msg || err.errMsg || '未知错误'}`
                    // );
                    getApp().mox.stat(`index page get_ads_config fail`);
                    RTLog.error(
                        'index page get_ads_config fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    reject(err);
                });
        });
    },
    toCreateInterstitialAd(adUnitId) {
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({ adUnitId: adUnitId });
            interstitialAd.onLoad(() => {
                interstitialAd.show().catch((err) => {
                    console.error(err);
                });
            });
            interstitialAd.onError((err) => {
                console.log('ad onError', err);
            });
            interstitialAd.onClose((res) => {
                console.log('ad onClose', res);
            });
        }
    },
    clickProductAd(e) {
        let test = e.currentTarget.dataset.test;
        getApp().$modules.advertise.handleAdClick(test, {
            ActivateVideoAd: this.xiguaAdMgrPool.getActivateVideoAd(test.adId)
        });
    },
    onTapProduct(evt) {
        let {
            type,
            appid = '',
            path = '',
            article_link = '',
            mpid = ''
        } = evt.currentTarget.dataset.item;
        if (type == 'article') {
            wx.navigateTo({
                url: '/pages/web/web?url=' + encodeURIComponent(article_link)
            });
        } else if (type == 'miniprogram') {
            wx.navigateToMiniProgram({
                appId: appid,
                path
            });
        } else if (type == 'pageviews') {
            // 提审页面
            wx.navigateTo({
                url: '/packageA/pages/date/date'
            });
        } else {
            wx.navigateTo({
                url: `/pages/testing/testing?mpid=${mpid}&is_from_home=0`
            });
            getApp().mox.stat('goto_product|all');
            getApp().mox.stat('goto_product|' + mpid.slice(-2));
        }
    },
    changeProduct() {
        let n = 3;
        let length = this.data.currentDataList.length;

        let result = length - this.data.count;
        let newArr = [];
        if (result > 0 && result <= n) {
            if (length === 1) {
                newArr = [...this.data.currentDataList.slice(length - result, length)];
            } else if (length === 2) {
                newArr = [...this.data.currentDataList.slice(0, length)];
            } else {
                newArr = [
                    ...this.data.currentDataList.slice(length - result, length),
                    ...this.data.currentDataList.slice(0, n - result)
                ];
            }
            this.data.count = n - result;
        } else if (result >= n) {
            newArr = this.data.currentDataList.slice(this.data.count, this.data.count + n);
            this.data.count += n;
        } else {
            this.data.count = 0;
            newArr = this.data.currentDataList.slice(this.data.count, this.data.count + n);
        }
        this.setData({
            showList: newArr
        });
    },
    gotoFeedback() {
        getApp().mox.stat('点击【反馈与投诉】');
        wx.navigateTo({
            url: '/pages/feedback/feedback'
        });
    }
});
